import 'dart:ui';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/components/app_bg_view.dart';
import 'package:pornhub_app/components/text_view.dart';
import 'package:pornhub_app/generate/app_image_path.dart';
import 'package:pornhub_app/routes/routes.dart';
import 'package:pornhub_app/utils/app_utils.dart';
import 'package:pornhub_app/utils/color.dart';
import 'package:pornhub_app/utils/extension.dart';
import 'package:tuple/tuple.dart';
import 'package:visibility_detector/visibility_detector.dart';

import '../../assets/assets.dart';
import '../../components/image_view.dart';
import '../../utils/utils.dart';
import 'mine_page_controller.dart';

class MinePage extends GetView<MinePageController> {
  const MinePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: COLOR.color_161616,
      body: _bodyView(),
    );
  }

  _bodyView() {
    return Column(
      children: [
        SizedBox(
          child: VisibilityDetector(
            key: const ValueKey("mine_page"),
            onVisibilityChanged: (info) {
              if (info.visibleFraction > 0) {
                controller.userService.updateAll();
              }
            },
            child: Container(
              height: 1.w,
              color: COLOR.color_333333,
            ),
          ),
        ),
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              children: [
                ///头部信息
                AppBar(
                  elevation: 0,
                  actions: [
                    IconButton(
                      onPressed: () => controller.onClick("设置"),
                      icon: Image.asset(
                        AppImagePath.mine_mine_setting,
                        width: 21.w,
                        height: 21.w,
                      ),
                    ),
                  ],
                  flexibleSpace: _buildbuildHeadView(),
                ),

                ///功能UI
                Container(
                  color: COLOR.color_161616,
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: Column(
                    children: [
                      12.verticalSpace,

                      ///充值和推广
                      // _buildRechargePromotionView(),

                      // ///隐藏APP
                      // GetPlatform.isAndroid
                      //     ? 12.verticalSpace
                      //     : 0.verticalSpace,
                      // GetPlatform.isAndroid
                      //     ? _buildHidAPPView()
                      //     : const SizedBox.shrink(),

                      ///我的  相关的
                      12.verticalSpace,
                      _buildFunctionView(),

                      ///活动
                      // 12.verticalSpace,
                      // Visibility(
                      //   visible: true,
                      //   child: InkWell(
                      //     onTap: () => controller.onClick("活动"),
                      //     child: Obx(() => ImageView(
                      //           src: controller.activityConfig.value.img ?? "",
                      //           width: double.infinity,
                      //           height: 52.w,
                      //           borderRadius: BorderRadius.circular(6.w),
                      //         )),
                      //   ),
                      // ),

                      // ///兑换会员、邀请码
                      // 12.verticalSpace,
                      // Container(
                      //   decoration: BoxDecoration(
                      //     color: COLOR.color_1D1D1D,
                      //     borderRadius: BorderRadius.circular(6.w),
                      //   ),
                      //   padding: EdgeInsets.symmetric(
                      //       horizontal: 16.w, vertical: 6.w),
                      //   child: Column(
                      //     mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      //     children: [
                      //       _buildOperateItemView(
                      //           AppImagePath.mine_mine_redeem_vip,
                      //           "兑换会员",
                      //           "填写兑换码"),
                      //       _buildOperateItemView(
                      //           AppImagePath.mine_mine_invite_code, "邀请码", ""),
                      //     ],
                      //   ),
                      // ),

                      // ///
                      // 25.verticalSpace,
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  ///头部信息
  _buildbuildHeadView() {
    return SizedBox(
      height: 240.w,
      child: Stack(
        children: [
          //头部背景
          _buildHeadBgView(),
          // //用户信息
          Positioned(
            top: 80.w,
            left: 0,
            right: 0,
            child: _buildUserInfoView(),
          ),

          ///会员信息
          Positioned(
              left: 14.w,
              right: 14.w,
              bottom: 0,
              child: GestureDetector(
                onTap: () => controller.onClick("VIP"),
                child: Container(
                  height: 70.w,
                  decoration: const BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(AppImagePath.mine_mine_vip_bg),
                      fit: BoxFit.fill,
                    ),
                  ),
                  padding: EdgeInsets.symmetric(horizontal: 8.w),
                  child: Obx(
                    () => Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        // ImageView(
                        //   src: AppImagePath.mine_mine_vip_logo,
                        //   width: 58.w,
                        //   height: 43.8.w,
                        // ),

                        Container(
                            margin: EdgeInsets.only(left: 68.w),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                TextView(
                                  text: '会员中心',
                                  fontSize: 15.w,
                                  color: COLOR.color_F3C5A7,
                                  textAlign: TextAlign.start,
                                ),
                                TextView(
                                  text: controller.userService.isVIP
                                      ? '到期时间：${Utils.dateFmt(controller.userService.user.expiredVip!, [
                                              "yyyy",
                                              "/",
                                              "mm",
                                              "/",
                                              "dd"
                                            ])}'
                                      : '开通会员，畅看海量视频',
                                  fontSize: 14.w,
                                  color: COLOR.color_F3C5A7,
                                  textAlign: TextAlign.start,
                                ),
                              ],
                            )),
                        AppBgView(
                          width: 76.w,
                          height: 32.w,
                          decoration: BoxDecoration(
                            color: COLOR.color_FABC8A,
                            borderRadius: BorderRadius.circular(15.w),
                          ),
                          text: controller.userService.isVIP ? "升级会员" : "立即开通",
                          textColor: COLOR.color_8d5527,
                        ),
                      ],
                    ),
                  ),
                ),
              )),
        ],
      ),
    );
  }

  ///头部背景
  _buildHeadBgView() {
    return Stack(
      children: [
        ImageView(
          src: AppImagePath.mine_mine_bg,
          width: double.infinity,
          height: 120.w,
          fit: BoxFit.fill,
        ),
        Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Container(
              height: 27.w,
              decoration: BoxDecoration(
                  color: COLOR.color_161616,
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(16.w),
                      topRight: Radius.circular(16.w))),
            ))
      ],
    );
  }

  ///用户信息
  _buildUserInfoView() {
    return Container(
      padding: EdgeInsets.only(left: 14.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ///加这个只是为了加载一个高度
          // AppBar(
          //   backgroundColor: Colors.transparent,
          //   shadowColor: Colors.transparent,
          //   automaticallyImplyLeading: false,
          // ),
          Row(
            children: [
              Stack(
                alignment: Alignment.bottomCenter,
                children: [
                  Obx(
                    () => Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(32.w)),
                        border: Border.all(color: COLOR.white, width: 1.5.w),
                      ),
                      child: ImageView(
                        src: "${controller.userService.user.logo}",
                        width: 64.w,
                        height: 64.w,
                        fit: BoxFit.cover,
                        borderRadius: BorderRadius.circular(43.w),
                        defaultPlace: Assets.avatarplaceholer,
                      ).onTap(() => Get.toUserHome(
                          userId: controller.userService.user.userId ?? 0)),
                    ),
                  ),
                  Obx(() => controller.userService.isVIP &&
                          AppUtils.getVipTypeToImagePath(
                                  controller.userService.user.vipType ?? 0)
                              .isNotEmpty
                      ? ImageView(
                          src: AppUtils.getVipTypeToImagePath(
                              controller.userService.user.vipType ?? 0),
                          height: 17.w,
                          fit: BoxFit.fitHeight,
                        )
                      : const SizedBox.shrink()),
                ],
              ),
              13.horizontalSpace,
              Expanded(
                  child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Obx(() => TextView(
                        text: controller.userService.user.nickName ?? '游客0000',
                        fontSize: 18.w,
                        color: COLOR.white,
                        maxLines: 1,
                        fontWeight: FontWeight.w500,
                        overflow: TextOverflow.ellipsis,
                      )),

                  ///畅聊会员标识
                  6.verticalSpace,
                  Obx(() => controller.userService.isChatVIP
                      ? Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            ImageView(
                              src: AppImagePath.mine_mine_chat_vip,
                              height: 17.w,
                            ),
                            3.horizontalSpace,
                            TextView(
                                text: "畅聊会员时间：${Utils.dateFmt(
                                  controller.userService.user.chatExpiredVip ??
                                      "",
                                  ["yyyy", "/", "mm", "/", "dd"],
                                )}",
                                fontSize: 11.w,
                                color: COLOR.white),
                          ],
                        )
                      : const SizedBox.shrink()),
                ],
              )),
            ],
          ),
          5.verticalSpace,
        ],
      ),
    );
  }

  ///充值推广
  _buildRechargePromotionView() {
    return Row(
      children: [
        Expanded(
          flex: 1,
          child: Obx(() => _buildRechargePromotionItemView(
                "金币充值",
                "当前余额：${(controller.userService.assets.gold ?? 0).toInt()}",
                AppImagePath.mine_mine_gold,
              )),
        ),
        10.horizontalSpace,
        Expanded(
          flex: 1,
          child: _buildRechargePromotionItemView(
            "推广赚钱",
            "邀请好友得VIP",
            AppImagePath.mine_mine_promotion,
          ),
        ),
      ],
    );
  }

  ///充值推广ItemView
  _buildRechargePromotionItemView(String title, String hint, String imagePath) {
    return GestureDetector(
      onTap: () => controller.onClick(title),
      child: Container(
        height: 60.w,
        decoration: BoxDecoration(
          color: COLOR.color_1D1D1D,
          borderRadius: BorderRadius.circular(6.w),
        ),
        padding: EdgeInsets.symmetric(horizontal: 15.w),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Expanded(
                child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                TextView(
                  text: title,
                  fontSize: 14.w,
                  color: COLOR.white,
                  textAlign: TextAlign.start,
                ),
                TextView(
                  text: hint,
                  fontSize: 12.w,
                  color: COLOR.white,
                  textAlign: TextAlign.start,
                ),
              ],
            )),
            Image.asset(
              imagePath,
              width: 37.w,
              height: 37.w,
            ),
          ],
        ),
      ),
    );
  }

  ///隐藏APP
  _buildHidAPPView() {
    var isShow = false.obs;
    return Container(
      decoration: BoxDecoration(
        color: COLOR.color_1D1D1D,
        borderRadius: BorderRadius.circular(6.w),
      ),
      padding: EdgeInsets.symmetric(vertical: 12.w),
      child: Column(
        children: [
          Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              child: Row(
                children: [
                  TextView(
                    text: "隐藏APP",
                    fontSize: 14.w,
                    color: COLOR.white,
                  ),
                  const Spacer(),
                  Obx(() => Icon(
                        isShow.value
                            ? Icons.keyboard_arrow_up_outlined
                            : Icons.keyboard_arrow_down_outlined,
                        color: COLOR.white,
                        size: 20.w,
                      )),
                ],
              )).onOpaqueTap(() {
            isShow.value = !isShow.value;
          }),
          Center(
            child: Obx(() => isShow.value
                ? GridView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    padding: EdgeInsets.only(top: 14.w),
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 5,
                    ),
                    itemCount: controller.hideApps.length,
                    itemBuilder: (BuildContext context, int index) {
                      Tuple2 tuple = controller.hideApps[index];
                      return _buildFunctionItemView(
                          tuple, Size(50.w, 50.w), 11.w);
                    },
                  )
                : const SizedBox.shrink()),
          ),
        ],
      ),
    );
  }

  ///我的  相关的
  _buildFunctionView() {
    return Container(
      // decoration: BoxDecoration(
      //   // color: COLOR.color_1D1D1D,
      //   borderRadius: BorderRadius.circular(6.w),
      // ),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        padding: EdgeInsets.only(top: 14.w),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 4, crossAxisSpacing: 9),
        itemCount: controller.myFunctions.length,
        itemBuilder: (BuildContext context, int index) {
          Tuple2 tuple = controller.myFunctions[index];
          return _buildFunctionItemView(tuple, Size(28.w, 28.w), 12.w);
        },
      ),
    );
  }

  _buildFunctionItemView(Tuple2 tuple, Size size, double textSize) {
    return GestureDetector(
      onTap: () => controller.onClick(tuple.item2),
      child: Container(
        width: 76.w,
        height: 70.w,
        decoration: BoxDecoration(
            image: DecorationImage(
                image: AssetImage(AppImagePath.mine_bg_function))),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Image.asset(
              tuple.item1,
              width: size.width,
              height: size.height,
            ),
            5.verticalSpace,
            TextView(
              text: tuple.item2,
              fontSize: textSize,
              color: COLOR.white,
            ),
          ],
        ),
      ),
    );
  }

  _buildOperateItemView(String imagePath, String title, String hint) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () => controller.onClick(title),
      child: SizedBox(
        height: 35.w,
        child: Row(
          children: [
            Image.asset(
              imagePath,
              width: 15.w,
              height: 15.w,
            ),
            6.horizontalSpace,
            TextView(
              text: title,
              fontSize: 12.w,
              color: COLOR.white,
            ),
            const Spacer(),
            TextView(
              text: hint,
              fontSize: 12.w,
              color: COLOR.white,
            ),
            7.horizontalSpace,
            Icon(
              Icons.chevron_right_outlined,
              color: COLOR.white,
              size: 20.w,
            ),
          ],
        ),
      ),
    );
  }
}
